import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:toast/toast.dart';

import 'base_app_bar.dart';
import 'package:event_bus/event_bus.dart';

abstract class BaseState<T> extends State {
  final TextEditingController textEditingController = TextEditingController();
  String loadingMsg = "正在加载...";
  String hint = "";
  String title = "";
  String code;
  String next = 'Next';
  int type = 1;
  bool feedback = false;
  bool _loading = false;
  var timeMillis = 0;

  // 创建全局EventBus实例
  EventBus eventBus = EventBus();

  Widget getViewBinding();

  String setTitle();

  void showFileUploadData(String path, int type, int position, bool isSubmit);

  void setReset();

  void setNext();

  // 下拉菜单更新选择
  void updateHint(String text) {
    setState(() {
      hint = text;
    });
  }

  void showDialogFunction() {
    _loading = true;
    setState(() {
      _loading = true;
    });
  }

  void hideDialogFunction() {
    setState(() {
      _loading = false;
    });
  }

  bool tvReset = true;

  void setResetGone() {
    setState(() {
      tvReset = false;
    });
  }

  bool tvNext = true;

  void setNextGone() {
    setState(() {
      tvNext = false;
    });
  }

  void setBackGone() {
    // titlebarBinding.ivBack.setVisibility(View.GONE);
  }

  bool baseLayoutBottom = true;

  void setLayoutBottomGone() {
    setState(() {
      baseLayoutBottom = false;
    });
  }

  bool baseLayoutBottomContent = true;

  void setLayoutBottomContentGone() {
    setState(() {
      baseLayoutBottomContent = false;
    });
  }

  IconData rightIcon = Icons.feedback_outlined;
  void setRightIcon(IconData icon) {
    setState(() {
      feedback=true;
      if(icon!=null){
        rightIcon = icon;
      }
    });
  }

  void setFeedBack() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(
        title: setTitle(),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.of(context).pop(true);
          },
        ),
        actions: [
          Visibility(
              visible: feedback,
              child: IconButton(
                icon: Icon(rightIcon,color: MyAppTheme.white,),
                onPressed: () {
                  setFeedBack();
                },
              )),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            flex: 1, //设置权重
            child: Container(
              color: MyAppTheme.color_f0f2f5,
              width: double.infinity,
              child: getViewBinding(),
            ),
          ),
          Visibility(
            visible: baseLayoutBottom,
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.only(left: 0, top: 2, right: 0),
              height: baseLayoutBottomContent ? 60 : 20,
              child: Column(
                children: [
                  Text(hint == null ? "" : hint, style: TextStyle(color: MyAppTheme.red, fontSize: 14.0)),
                  Visibility(
                      visible: baseLayoutBottomContent,
                      child: Container(
                        margin: EdgeInsets.only(left: 7.5, right: 7.5),
                        child: Row(
                          children: [
                            Visibility(
                              visible: tvReset,
                              child: Expanded(
                                flex: 1, //设置权重
                                child: Container(
                                  margin: EdgeInsets.only(left: 7.5, right: 7.5),
                                  child: SizedBox(
                                    height: 40, // 高度
                                    child: ElevatedButton(
                                      child: Text('Reset'),
                                      style: ButtonStyle(
                                        backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                                        shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                          RoundedRectangleBorder(
                                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                                          ),
                                        ),
                                      ),
                                      onPressed: () {
                                        setReset();
                                      },
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            Visibility(
                              visible: tvNext,
                              child: Expanded(
                                flex: 1, //设置权重
                                child: Container(
                                  margin: EdgeInsets.only(left: 7.5, right: 7.5),
                                  child: SizedBox(
                                    height: 40, // 高度
                                    child: ElevatedButton(
                                      child: Text(next),
                                      style: ButtonStyle(
                                        backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                                        shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                          RoundedRectangleBorder(
                                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                                          ),
                                        ),
                                      ),
                                      onPressed: () {
                                        setNext();
                                      },
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ))
                ],
              ),
            ),
          ),
        ],
      ),
      // bottomSheet: Visibility(
      //   visible: baseLayoutBottom,
      //   child: Container(
      //     width: double.infinity,
      //     padding: const EdgeInsets.only(left: 0, top: 2, right: 0),
      //     height: baseLayoutBottomContent ? 60 : 20,
      //     child: Column(
      //       children: [
      //         Text(hint == null ? "" : hint, style: TextStyle(color: MyAppTheme.red, fontSize: 14.0)),
      //         Visibility(
      //             visible: baseLayoutBottomContent,
      //             child: Container(
      //               margin: EdgeInsets.only(left: 7.5, right: 7.5),
      //               child: Row(
      //                 children: [
      //                   Expanded(
      //                     flex: 1, //设置权重
      //                     child: Container(
      //                       margin: EdgeInsets.only(left: 7.5, right: 7.5),
      //                       child: SizedBox(
      //                         height: 40, // 高度
      //                         child: ElevatedButton(
      //                           child: Text('Reset'),
      //                           style: ButtonStyle(
      //                             backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
      //                             shape: MaterialStateProperty.all<RoundedRectangleBorder>(
      //                               RoundedRectangleBorder(
      //                                 borderRadius: const BorderRadius.all(Radius.circular(20.0)),
      //                               ),
      //                             ),
      //                           ),
      //                           onPressed: () {
      //                             setReset();
      //                           },
      //                         ),
      //                       ),
      //                     ),
      //                   ),
      //                   Expanded(
      //                     flex: 1, //设置权重
      //                     child: Container(
      //                       margin: EdgeInsets.only(left: 7.5, right: 7.5),
      //                       child: SizedBox(
      //                         height: 40, // 高度
      //                         child: ElevatedButton(
      //                           child: Text('Next'),
      //                           style: ButtonStyle(
      //                             backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
      //                             shape: MaterialStateProperty.all<RoundedRectangleBorder>(
      //                               RoundedRectangleBorder(
      //                                 borderRadius: const BorderRadius.all(Radius.circular(20.0)),
      //                               ),
      //                             ),
      //                           ),
      //                           onPressed: () {
      //                             setNext();
      //                           },
      //                         ),
      //                       ),
      //                     ),
      //                   ),
      //                 ],
      //               ),
      //             ))
      //       ],
      //     ),
      //   ),
      // ),
    );
  }

  void imgDialog(String path) async {
    var result = await showDialog(
        barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            content: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Image.asset(
                path,
                fit: BoxFit.cover,
              ),
            ),
          );
        });

    print(result);
  }

  void imgFileDialog(PhotoBean photoBean, String baseImgUrl) async {
    var result = await showDialog(
        barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            content: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: photoBean.image != null
                  ? Image.file(
                      photoBean.image,
                      fit: BoxFit.cover,
                    )
                  : Image.network(
                      baseImgUrl + photoBean.urlImg,
                      fit: BoxFit.cover,
                    ),
            ),
          );
        });

    print(result);
  }

  Future<Directory> getLocalPath() async {
    final directory = await getApplicationDocumentsDirectory();
    print("directory${directory.path}");
    return directory;
  }

  // void fileUpload(String containerNo, String func, File file, String fileName, int type, int position, bool isSubmit, bool showDialog) async {
  //   updateHint('');
  //   DateTime currentTime = DateTime.now();
  //   String timestamp = '${currentTime.millisecondsSinceEpoch}';
  //   String name = containerNo + "/" + fileName + timestamp + ".jpg";
  //   print("name: $name");
  //
  //   var bytes = await file.readAsBytes();
  //   // 使用FormData上传
  //   FormData formData = FormData.fromMap({"file": await MultipartFile.fromBytes(bytes, filename: "image.png")});
  //
  //   Map<String, dynamic> map = new HashMap();
  //
  //   map["containerNo"] = containerNo;
  //   map["function"] = func;
  //   map["fileName"] = fileName + timestamp;
  //   map["path"] = name;
  //
  //   if (showDialog) {
  //     LoadingIndicator.show(context);
  //   }
  //
  //   BaseResponse baseResponse = await NetworkManager().request(context, Constants.wmsFileUpload, method: BaseMethod.post, params: map, data: formData);
  //   if (showDialog) {
  //     LoadingIndicator.hide();
  //   }
  //
  //   if (baseResponse.status == 200) {
  //     showFileUploadData(name, type, position, isSubmit);
  //   } else {
  //     if (isSubmit) {
  //       updateHint(baseResponse.msg);
  //       ToastContext().init(context);
  //       Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
  //     }
  //   }
  // }
  void fileUpload(String containerNo, String func, File file, String fileName, int type, int position, bool isSubmit, bool showDialog) async {
    updateHint('');
    DateTime currentTime = DateTime.now();
    String timestamp = '${currentTime.millisecondsSinceEpoch}';
    String name = "wms/" + containerNo + "/" + fileName + timestamp + ".jpg";
    print("name: $name");

    BlobStorage blobStorage = new BlobStorage();
    blobStorage.blobName = name;

    if (showDialog) {
      LoadingIndicator.show(context);
    }
    String json = jsonEncode(blobStorage);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.storageUrl, method: BaseMethod.post, data: json);
    if (showDialog) {
      LoadingIndicator.hide();
    }

    if (baseResponse.status == 200) {
      String url = baseResponse.data;
      uploadGoogleCloud(url, name, file, fileName, type, position, isSubmit, showDialog);
    } else {
      if (isSubmit) {
        updateHint(baseResponse.msg);
        ToastContext().init(context);
        Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
      }
    }
  }

  void uploadGoogleCloud(String url, String name, File file, String fileName, int type, int position, bool isSubmit, bool showDialog) async {
    var bytes = await file.readAsBytes();
    // 使用FormData上传
    FormData formData = FormData.fromMap({"file": await MultipartFile.fromBytes(bytes, filename: "image.png")});
    if (showDialog) {
      LoadingIndicator.show(context);
    }

    Response baseResponse = await NetworkManager().requestUpload(context, url, method: BaseMethod.put, data: bytes);
    if (showDialog) {
      LoadingIndicator.hide();
    }

    if (baseResponse.statusCode == 200) {
      showFileUploadData(name, type, position, isSubmit);
    } else {
      if (isSubmit) {
        updateHint(baseResponse.statusMessage);
        ToastContext().init(context);
        Toast.show(Utils.getStringisEmpty(baseResponse.statusMessage), duration: Toast.lengthShort, gravity: Toast.bottom);
      }
    }

    // String baseResponse = await NetworkManager().uploadBytes( url,bytes);
    // if (showDialog) {
    //   LoadingIndicator.hide();
    // }

    // if (baseResponse.statusCode == 200) {
    //   showFileUploadData(name, type, position, isSubmit);
    // } else {
    //   if (isSubmit) {
    //     // updateHint(baseResponse.msg);
    //     // ToastContext().init(context);
    //     // Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    //   }
    // }
  }
}

class BlobStorage {
  String blobName;
  String method = "PUT";
  String contentType = "application/octet-stream";

  Map<String, dynamic> toJson() => {
        'blobName': blobName,
        'method': method,
        'contentType': contentType,
      };
}
